
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rfid/util/toast_util.dart';
import '../entity/setting_entity.dart';
import '../hive/hive_helper.dart';
import '../http/api.dart';
import '../main.dart';
import '../widget/device_name_widget.dart';
import '../widget/focus_killer.dart';



class DistributedBook extends StatefulWidget {
  const DistributedBook({Key? key}) : super(key: key);

  @override
  State<DistributedBook> createState() => _DistributedBookState();
}

class _DistributedBookState extends State<DistributedBook> {

  late List<SettingEntityReader> _lists;
  final RxList<SettingEntityReader> _list = RxList();
  var pageIndex = 1;
  var pageSize = 32;
  var total = 0;

  @override
  initState() {
    super.initState();
    if(settingEntity.reader != null && settingEntity.reader!.isNotEmpty){
      _lists = settingEntity.reader!.where((element) => element.state! == 0).toList();
      total = books.length;
      _subList();
    }else{
      toastWarn('未配置格口');
    }
  }


  _subList(){

    if(pageIndex<1){
      pageIndex = 1;
    }
    if(_lists.length > pageIndex*pageSize){
      _list.clear();
      _list.addAll(_lists.sublist((pageIndex-1)*pageSize,pageIndex*pageSize));
    }else if(_lists.length <= pageIndex*pageSize && _lists.length > (pageIndex-1)*pageSize){
      _list.clear();
      _list.addAll(_lists.sublist((pageIndex-1)*pageSize,_lists.length));
    }else{
      pageIndex--;
    }

  }


  _appBar(){
    return Container(
      width: double.infinity,
      height: 42.h,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 20,right: 20).w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          deviceNameWidget(),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              focusKiller(),
              Text(" ",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
            ],
          )

        ],
      ),
    );
  }

  _title(){
    return Container(
      margin: EdgeInsets.only(top: 20.h,left: 20.w,right: 20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: (){
              Get.back();
            },
            child: _image("assets/images/back.png",60.w,23.h),
          ),
          _image("assets/images/distributed_book_title.png",90.w,21.h),
          Text("总量:$total",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
        ],
      )
    );
  }

  _divider(){
    return Divider(
      height: 0.5.h, // Divider 组件高度
      indent: 4.w, // 分割线左侧间距
      endIndent: 4.w, // 分割线右侧间距
      color: const Color.fromRGBO(86, 169, 255, 1),
    );
  }

  _listLabel(){
    return Container(
        padding: EdgeInsets.only(top: 2.h,bottom: 2.h),
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        child: Row(
          // mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _label('序号',50.w),
            _label('图书条码号',105.w),
            _label('图书名称',105.w),
            _label('状态',40.w),
          ],
        )
    );
  }

  _label(text,width){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: Colors.blueAccent,fontSize: 10.sp),textAlign: TextAlign.center,),
    );
  }

  _listTitle(){
    return Container(
      // width: 300.w,
      height: 20.h,
      decoration: BoxDecoration(
        color: const Color.fromRGBO(86, 169, 255, 1),
        borderRadius: BorderRadius.only(topLeft:Radius.circular(4.r),topRight: Radius.circular(4.r)),
      ),
      alignment: Alignment.center,
      child: Text('图书清单',style: TextStyle(color: Colors.white,fontSize: 10.sp,fontWeight: FontWeight.bold),),
    );
  }

  _item(text,width,{Color color = Colors.black}){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: color,fontSize: 8.sp),textAlign: TextAlign.center,),
    );
  }

  _listItem(books,index){
    var item = books[index];

    return Container(
        padding: EdgeInsets.only(top: 2.h,bottom: 2.h),
        child: Row(
          // mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _item('${index+1}',50.w),
            _item('${item.no}',105.w),
            _item('${item.mainTitle}',105.w),
            _item(item.statue==0?'在架':'外借',40.w),
          ],
        )
    );
  }

  _bList(books){
    return Expanded(child: ListView.separated(
      itemBuilder: (context, index) {
        return _listItem(books,index);
      },
      itemCount: books.length,
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          height: 0.5.h, // Divider 组件高度
          // thickness: 5, // 分割线线宽，分割线居于 Divider 中心
          indent: 4.w, // 分割线左侧间距
          endIndent: 4.w, // 分割线右侧间距
          color: Colors.grey,
        );
      },
    ));
  }

  _listWidget(books){
    return Container(
      width: 330.w,
      height: 420.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      child: Column(
        children: [
          _listTitle(),
          _listLabel(),
          _divider(),
          _bList(books)

        ],
      ),

    );
  }

  _resultListDialog(books){
    Get.defaultDialog(
      title: "",
      barrierDismissible: false,
      contentPadding:EdgeInsets.zero,
      titlePadding:EdgeInsets.zero,
      backgroundColor: Colors.transparent,
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _listWidget(books),
          SizedBox(height: 10.h,),
          Row(mainAxisAlignment:MainAxisAlignment.center, children: [_synchronize(books),_confirm()],)
        ],
      )
    );
  }

  _synchronize(books){
    return InkWell(
      onTap: () async {
        BotToast.showLoading();
        for(var item in books){
          var book = await searchBook(item);
          if(book != null){
           bookInsert(book.no, book);
          }
        }
        BotToast.closeAllLoading();
      },
      child:  _image("assets/images/synchronize.jpg", 80.w, 36.h),
    );
  }
  _confirm(){
    return InkWell(
      onTap: () async {
        Get.back();
      },
      child:  _image("assets/images/result_confirm.jpg", 80.w, 36.h),
    );
  }


  _itemBuilder(index){
    var item = _list[index];
    var books = bookQueryByDoorNo(item.doorNo!);
    var bookNum = books.length;
    return InkWell(
      onTap: (){
        _resultListDialog(books);
      },
      child: Stack(
        alignment: Alignment.center,
        children: [
          _image("assets/images/distributed_bg.png", 100.w, 70.h),
          Positioned(
            right: 9.w,
            top: 7.5.h,
            child: Text('$bookNum本',style: TextStyle(color: Colors.white,fontSize: 6.sp),),
          ),
          Text('格口${item.doorNo}',style: TextStyle(color: Colors.blueAccent,fontSize: 8.sp),),

        ],
      ),
    );
  }

  _booksContainer(){
    return Container(
      margin: EdgeInsets.only(left: 20.w,right: 20.w,top: 20.h),
      width: double.infinity,
      height: 460.h,
      child: Obx(() => GridView.builder(
        itemBuilder: (context, index) {
          return _itemBuilder(index);
        },
        itemCount: _list.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4,childAspectRatio:1.42,  crossAxisSpacing: 5.w),
      ),)
    );
  }

  _action(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        InkWell(
          onTap: (){
            pageIndex--;
            _subList();
          },
          child:  _image("assets/images/previous.png", 80.w, 36.h),
        ),
        InkWell(
          onTap: (){
            pageIndex++;
            _subList();
          },
          child:   _image("assets/images/next.png", 80.w, 36.h),
        )
      ],
    );
  }


  _image(name,width, height){
    return Image.asset(name,height: height, width: width, fit: BoxFit.fill,);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            _appBar(),
            _title(),
            _booksContainer(),
            _action(),
          ],
        ),
      ),
    );
  }
}

